<template>
  <div>
    <div className="hello">
      <TimePicker
          @time-range-selected="handleTimeSelected"
      ></TimePicker>
      <div style="height: 10px">
        <strong style="display: block; text-align: center; font-size: 40px"
        >DBZ</strong
        >
      </div>
      <div className="box">
        <div className="chart">
          <div id="charts" ref="chart"></div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {onMounted, onUnmounted, reactive, ref} from "vue";
import 'echarts-gl';
import 'echarts/map/js/province/guangdong.js';
import geoJson from '../assets/yuegangao.json';
import 'echarts-extension-amap';
import {useStore} from 'vuex'; // 引入useStore 方法
import {getDBZData} from '@/api/user/dbz';
import regionStylesData from "../assets/regionStyles.json";
import TimePicker from './TimePicker'

export default {
  name: "radar",

  components: {
    TimePicker,
  },

  setup() {
    const store = useStore()  // 该方法用于返回store 实例
    let myEcharts = echarts;
    let chart = null;
    let cooData = ref([])
    let params = {
      year: 2023,
      month: 4,
      day: 26,
      hour: 6,
      minute: 18
    };

    let arrayData = reactive({
      arrData: []
    });

    function handleTimeSelected(selectedTime) {
      console.log("time", selectedTime)
      const {date, start} = selectedTime;
      // 分割日期和时间
      const [year, month, day] = date.split('-');
      const [hours, minutes] = start.split(':');
      params.year = year
      params.month = month
      params.day = day
      params.hour = hours
      params.minute = minutes
      console.log('params:', params);
      initChart()
    }

    onMounted(() => {
      initChart();
    });


    onUnmounted(() => {
      myEcharts.dispose;
      chart.dispose();
      chart = null;
    });

    async function initChart() {

      let StartLat = 27.0
      let StartLon = 108.5
      let XReso = 0.01
      let YReso = 0.01

      cooData = await fetchCOOData(params);
      console.log("cooData", cooData)
      arrayData.arrData = await updateArrayData()

      let data = []
      for (const item of arrayData.arrData) {
        const lon = StartLon + item[1] * XReso
        const lat = StartLat - item[0] * YReso
        data.push([lon, lat, item[2]])
      }
      const guangdongCenter = [113.280637, 23.125178];
      chart = myEcharts.init(document.getElementById("charts"), "purple-passion");
      // 注册可用的地图
      myEcharts.registerMap('guangdong', geoJson);
      await loadRegionStyles(chart);//突出大湾区线条
      // 设置echarts的option
      chart.setOption({
        // title: {
        //   text: '标题',
        //   subtext: '子标题',
        //   x: 'center'
        // },
        tooltip: {
          show: true,
          trigger: 'item',
          alwaysShowContent: false,
        },
        visualMap: {
          min: 0,
          max: 30,
          inverse: true,
          calculable: true,
          orient: "vertical",
          left: "right",
          bottom: "3%",
          inRange: {
            color: ["white", "blue", "yellow", "red"],
          },
          textStyle: {
            color: '#fff',
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        geo: {
          map: 'guangdong',
          center: guangdongCenter,
          aspectScale: 1, //长宽比
          zoom: 7,
          roam: true,
          itemStyle: {
            normal: {
              borderColor: '#f4f4f4',
              areaColor: '#fff',
              shadowColor: '#182f68',
              shadowOffsetX: 0,
              shadowOffsetY: 1,
            },
            emphasis: {
              areaColor: '#fff',
              borderWidth: 0,
              label: {
                show: false
              }
            }
          },
          scaleLimit:{
            min:5,                          //最小的缩放值
            max:30,                            //最大的缩放值
          }
        },

        series: [
          {
            type: 'scatter',
            symbol: 'rect',
            symbolSize: 5,
            coordinateSystem: 'geo',
            animation: false,
            emphasis: {//强调
              itemStyle: {
                color: 'blue'
              }
            },
            encode: {
              tooltip: 2
            },
            data: data
          },
        ],
      });
      window.onresize = function () {
        chart.resize();
      };
    }

    async function loadRegionStyles(chart) {
      try {
        // 使用导入的 JSON 数据
        const regionStyles = regionStylesData;
        chart.setOption({
          geo: {
            regions: regionStyles.regions,
          },
        });
      } catch (error) {
        console.error('Error loading region styles:', error);
      }
    }

    async function fetchCOOData(params) {
      try {
        let cooData1 = await getDBZData(params);// 使用接口文件中的函数获取数据
        return cooData1
      } catch (error) {
        console.error('Error fetching COO data:', error);
      }
    }

    async function updateArrayData() {
      let array = cooData.map(item => item.coo);
      return array[0]
    }

    return {
      arrayData,
      cooData,
      handleTimeSelected,
    }
  }
}
</script>

<style scoped lang="scss">
.head-name {
  color: #b0e3ff;
  font-weight: bold;
  font-size: xx-large;
  padding: 50px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}


@media screen and (min-width: 700px) {
  .chart {
    border: 3px double #c7e8ff;
    background-color: #6c8fff;
    margin: 60px;
    width: 70%;
    height: 65vh;

    #charts {
      width: 100%;
      height: 65vh
    }
  }
}


</style>
